package com.miracle9.game.service;

import com.miracle9.game.dao.AdminServiceDao;
import com.miracle9.game.dao.AdminLogServiceDao;
import com.miracle9.game.dao.BusineServiceDao;
import com.miracle9.game.dao.BusineInfoServiceDao;
import com.miracle9.game.dao.BusineInfoTempServiceDao;
import com.miracle9.game.dao.BusineLogServiceDao;
import com.miracle9.game.dao.SystemConfigServiceDao;
import com.miracle9.game.dao.UserAwardServiceDao;
import com.miracle9.game.dao.UserServiceDao;
import com.miracle9.game.dao.ComputerOrderServiceDao;
import com.miracle9.game.bean.Pager;
import com.miracle9.game.entity.Admin;
import com.miracle9.game.entity.AdminLog;
import com.miracle9.game.entity.Busine;
import com.miracle9.game.entity.BusineInfo;
import com.miracle9.game.entity.BusineInfoTemp;
import com.miracle9.game.entity.BusineLog;
import com.miracle9.game.entity.BusineLog.BusineType;
import com.miracle9.game.entity.ComputerOrder;
import com.miracle9.game.entity.SystemConfig;
import com.miracle9.game.entity.User;
import com.miracle9.game.util.MyUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("computerOrderService")
public class ComputerOrderService
  extends BaseService
{
  @Autowired
  private ComputerOrderServiceDao computerOrderServiceDao;
  @Autowired
  private UserServiceDao userServiceDao;
  @Autowired
  private AdminLogServiceDao adminLogServiceDao;
  @Autowired
  private AdminServiceDao adminServiceDao;
  @Autowired
  private UserAwardServiceDao userAwardServiceDao;
  @Autowired
  private BusineServiceDao busineServiceDao;
  @Autowired
  private BusineInfoServiceDao busineInfoServiceDao;
  @Autowired
  private SystemConfigServiceDao systemConfigServiceDao;
  @Autowired
  private BusineInfoTempServiceDao busineInfoTempServiceDao;
  @Autowired
  private BusineLogServiceDao busineLogServiceDao;
  
  public synchronized Map<String, Object> borrow(int userId, int deposit, String remark, IoSession session)
  {
    if (deposit < 0) {
      deposit = -deposit;
    }
    Map<String, Object> result = new HashMap();
    User user = (User)this.userServiceDao.getById(Integer.valueOf(userId));
    Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
    Admin admin = (Admin)this.adminServiceDao.getById(adminId);
    Busine busine = this.busineServiceDao.getAndSave();
    SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
    if (getQuantityById(userId))
    {
      result.put("success", Boolean.valueOf(false));
      result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "existZhujie"));
      result.put("plusGold", Integer.valueOf(0));
      return result;
    }
    int waiter = admin.getType() == 3 ? 1 : 0;
    if (config.getSwitchType() != -1)
    {
      if ((busine.getStatus() != 0) && (admin.getType() == 3))
      {
        result.put("success", Boolean.valueOf(false));
        result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "pauseBusine"));
        result.put("plusGold", Integer.valueOf(0));
        return result;
      }
      if (busine.getStatus() == 2)
      {
        this.busineInfoTempServiceDao.save(new BusineInfoTemp(admin.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), 0, 0.0D, 
          deposit, 0));
      }
      else
      {
        BusineInfo info = this.busineInfoServiceDao.getBusineInfo(admin.getUsername(), busine.getId(), 
          busine.getCurrentShiftType());
        if (info == null)
        {
          info = new BusineInfo();
          info.setBusineId(busine.getId());
          info.setCurrentShiftType(busine.getCurrentShiftType());
          info.setStartTime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
          info.setTakeDeposit(deposit);
          info.setAdmin(admin.getUsername());
          info.setWaiter(waiter);
          this.busineInfoServiceDao.save(info);
        }
        else
        {
          if (info.getShiftWorkStatus() == 1)
          {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "jiaobanOperationError"));
            result.put("plusGold", Integer.valueOf(0));
            return result;
          }
          info.setTakeDeposit(info.getTakeDeposit() + deposit);
          this.busineInfoServiceDao.update(info);
        }
      }
      this.busineLogServiceDao.save(new BusineLog(user.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), deposit, 0, admin
        .getUsername(), BusineLog.BusineType.LEASE));
    }
    ComputerOrder order = new ComputerOrder();
    order.setUser(user);
    order.setBorrowDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
    order.setDeposit(deposit);
    order.setStatus(0);
    order.setRemark(remark + "（收取" + deposit + "元）");
    order.setAdmin(admin.getUsername());
    order.setBorrowAuthority(admin.getType());
    this.computerOrderServiceDao.save(order);
    result.put("success", Boolean.valueOf(true));
    result.put("message", "");
    
    AdminLog adminLog = new AdminLog(admin.getUsername(), "为直属会员" + user.getUsername() + "租借平板电脑", 2, 
      admin.getType(), "Rent Pad for direct member which ID is " + user.getUsername());
    this.adminLogServiceDao.addAdminLog(adminLog);
    return result;
  }
  
  public Map<String, Object> repay(int userId, int deposit, String remark, IoSession session)
  {
    Map<String, Object> result = new HashMap();
    User user = (User)this.userServiceDao.getById(Integer.valueOf(userId));
    Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
    Admin admin = (Admin)this.adminServiceDao.getById(adminId);
    
    ComputerOrder order = (ComputerOrder)this.computerOrderServiceDao.q_CreateSqlFilter("from ComputerOrder where user.id=? and status=0", new Object[] {
      Integer.valueOf(user.getId()) });
    if (order != null)
    {
      Busine busine = this.busineServiceDao.getAndSave();
      SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
      int waiter = admin.getType() == 3 ? 1 : 0;
      if (config.getSwitchType() != -1)
      {
        if ((busine.getStatus() != 0) && (admin.getType() == 3))
        {
          result.put("success", Boolean.valueOf(false));
          result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "pauseBusine"));
          result.put("plusGold", Integer.valueOf(0));
          return result;
        }
        if (busine.getStatus() == 2)
        {
          this.busineInfoTempServiceDao.save(new BusineInfoTemp(admin.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), 0, 
            0.0D, 0, deposit));
        }
        else
        {
          BusineInfo info = this.busineInfoServiceDao.getBusineInfo(admin.getUsername(), busine.getId(), 
            busine.getCurrentShiftType());
          if (info == null)
          {
            info = new BusineInfo();
            info.setBusineId(busine.getId());
            info.setCurrentShiftType(busine.getCurrentShiftType());
            info.setStartTime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
            info.setReturnDeposit(deposit);
            info.setAdmin(admin.getUsername());
            info.setWaiter(waiter);
            this.busineInfoServiceDao.save(info);
          }
          else
          {
            if (info.getShiftWorkStatus() == 1)
            {
              result.put("success", Boolean.valueOf(false));
              result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "jiaobanOperationError"));
              result.put("plusGold", Integer.valueOf(0));
              return result;
            }
            info.setReturnDeposit(info.getReturnDeposit() + deposit);
            this.busineInfoServiceDao.update(info);
          }
        }
        this.busineLogServiceDao.save(new BusineLog(user.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), deposit, 0, admin
          .getUsername(), BusineLog.BusineType.GIVE));
      }
      order.setReturnDeposit(deposit);
      order.setRepayRemark(remark + "（归还" + deposit + "元）");
      order.setRepayAdmin(admin.getUsername());
      order.setRepayAuthority(admin.getType());
      order.setRepayDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
      order.setStatus(1);
      this.computerOrderServiceDao.update(order);
      result.put("success", Boolean.valueOf(true));
      result.put("message", "");
      
      AdminLog adminLog = new AdminLog(admin.getUsername(), "为直属会员" + user.getUsername() + "归还平板电脑", 
        2, admin.getType(), "Reture Pad for direct member which ID is " + user.getUsername());
      this.adminLogServiceDao.addAdminLog(adminLog);
    }
    else
    {
      result.put("success", Boolean.valueOf(false));
      result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notZhujie"));
    }
    return result;
  }
  
  public Map<String, Object> getUserOrder(int userId, String startDate, String endDate, Pager pager, IoSession session)
  {
    Map<String, Object> map = new HashMap();
    endDate = MyUtil.DateByDayCalendar(endDate, 1);
    pager = this.computerOrderServiceDao.q_CreateSqlsPager(
      "from ComputerOrder where user.id=? and borrowDate>=? and borrowDate<?", pager, new Object[] { Integer.valueOf(userId), startDate, 
      endDate });
    List<Object> datas = new ArrayList();
    for (Object o : pager.getList())
    {
      ComputerOrder co = (ComputerOrder)o;
      Map<String, Object> data = new HashMap();
      data.put("borrowDate", co.getBorrowDate());
      data.put("repayDate", co.getRepayDate());
      data.put("user", co.getUser().getUsername());
      data.put(
        "status", 
        co.getStatus() == 0 ? MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notReturn") : MyUtil.getProperties(
        Integer.valueOf(resultInt(session)), "alreadyReturn"));
      data.put("deposit", Integer.valueOf(co.getDeposit()));
      
      data.put("returnDeposit", co.getStatus() == 0 ? "" : Integer.valueOf(co.getReturnDeposit()));
      data.put("remark", co.getRemark());
      data.put("repayRemark", co.getRepayRemark());
      data.put("admin", co.getAdmin());
      data.put("repayAdmin", co.getRepayAdmin());
      datas.add(data);
    }
    pager.setList(datas.toArray());
    map.put("pager", pager);
    return map;
  }
  
  public Pager getOutOrder(Pager pager, IoSession session)
  {
    List<Object> datas = new ArrayList();
    String orgOrderBy = pager.getOrderBy();
    if ((orgOrderBy != null) && (orgOrderBy.equals("gameGold"))) {
      pager.setOrderBy("user.gameGold");
    }
    pager = this.computerOrderServiceDao.q_CreateSqlsPager("from ComputerOrder where status=0 and user.promoterId=0", pager, new Object[0]);
    for (Object o : pager.getList())
    {
      ComputerOrder co = (ComputerOrder)o;
      Map<String, Object> data = new HashMap();
      data.put("user", co.getUser().getUsername());
      data.put("gameGold", Integer.valueOf(co.getUser().getGameGold()));
      data.put("borrowDate", co.getBorrowDate());
      data.put("deposit", Integer.valueOf(co.getDeposit()));
      data.put("remark", co.getRemark());
      data.put("admin", co.getAdmin());
      datas.add(data);
    }
    pager.setList(datas.toArray());
    pager.setOrderBy(orgOrderBy);
    return pager;
  }
  
  public Pager getOrderLog(String startDate, String endDate, Pager pager, IoSession session)
  {
    endDate = MyUtil.DateByDayCalendar(endDate, 1);
    pager = this.computerOrderServiceDao.q_CreateSqlsPager("from ComputerOrder where borrowDate>=? and borrowDate<? and user.promoterId=0", pager, new Object[] {
      startDate, endDate });
    List<Object> datas = new ArrayList();
    for (Object o : pager.getList())
    {
      ComputerOrder co = (ComputerOrder)o;
      Map<String, Object> data = new HashMap();
      data.put("borrowDate", co.getBorrowDate());
      data.put("repayDate", co.getRepayDate());
      data.put("user", co.getUser().getUsername());
      data.put(
        "status", 
        co.getStatus() == 0 ? MyUtil.getProperties(Integer.valueOf(resultInt(session)), "notReturn") : MyUtil.getProperties(
        Integer.valueOf(resultInt(session)), "alreadyReturn"));
      data.put("deposit", Integer.valueOf(co.getDeposit()));
      data.put("returnDeposit", co.getStatus() == 0 ? "" : Integer.valueOf(co.getReturnDeposit()));
      data.put("remark", co.getRemark());
      data.put("repayRemark", co.getRepayRemark());
      data.put("admin", co.getAdmin());
      data.put("repayAdmin", co.getRepayAdmin());
      datas.add(data);
    }
    pager.setList(datas.toArray());
    return pager;
  }
  
  public int getOrderDeposit(int userId, IoSession session)
  {
    ComputerOrder order = (ComputerOrder)this.computerOrderServiceDao.q_CreateSqlFilter("from ComputerOrder where user.id=? and status=0", new Object[] { Integer.valueOf(userId) });
    return order == null ? 0 : order.getDeposit();
  }
  
  private boolean getQuantityById(int userId)
  {
    int count = this.computerOrderServiceDao.q_CreateSqlInt("select count(*) from ComputerOrder where user.id=? and status=0", new Object[] {
      Integer.valueOf(userId) });
    return count > 0;
  }
  
  public void deletePastOrder(String date)
  {
    this.computerOrderServiceDao.deletePastOrder(date);
  }
}
